package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.example.constant.ResultCodeConstant;
import com.example.dos.AwardDO;
import com.example.dto.AwardDTO;
import com.example.dto.AwardExportDTO;
import com.example.dto.AwardImportDTO;
import com.example.exception.BusinessException;
import com.example.mapper.AwardMapper;
import com.example.service.AwardService;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *   获奖信息服务层实现类
 * </p>
 * @author 34448
 */
@Slf4j
@Service
public class AwardServiceImpl implements AwardService {

    @Autowired
    private AwardMapper awardMapper;

    @Override
    @Transactional
    public Boolean addAward(AwardDTO awardDTO) {
        QueryWrapper<AwardDO> wrapper = Wrappers.query();
        wrapper.eq("award_name", awardDTO.getAwardName())
                .eq("award_date", awardDTO.getAwardDate())
                .eq("competition_name", awardDTO.getCompetitionName())
                .eq("teacher_id", awardDTO.getTeacherId())
                .eq("team_members", awardDTO.getTeamMembers())
                .eq("student_ids", awardDTO.getStudentIds())
                .eq("certificate_url", awardDTO.getCertificateUrl());

        AwardDO existingAward = awardMapper.selectOne(wrapper);
        if (existingAward != null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG);
        }

        AwardDO awardDO = new AwardDO();
        awardDO.setAwardName(awardDTO.getAwardName());
        awardDO.setAwardDate(awardDTO.getAwardDate());
        awardDO.setCompetitionName(awardDTO.getCompetitionName());
        awardDO.setTeacherId(awardDTO.getTeacherId());
        awardDO.setTeamMembers(awardDTO.getTeamMembers());
        awardDO.setStudentIds(awardDTO.getStudentIds());
        awardDO.setCertificateUrl(awardDTO.getCertificateUrl());
        awardDO.setCreateBy(1); // Assuming current user ID is 1
        awardDO.setCreateTime(new Date());
        awardDO.setUpdateBy(1); // Assuming current user ID is 1
        awardDO.setUpdateTime(new Date());

        return awardMapper.insert(awardDO) > 0;
    }

    @Override
    @Transactional
    public Boolean deleteAward(Integer awardId) {
        AwardDO existingAward = awardMapper.selectById(awardId);
        if (existingAward == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "获奖信息不存在");
        }

        return awardMapper.deleteById(awardId) > 0;
    }

    @Override
    @Transactional
    public Boolean updateAward(AwardDTO awardDTO) {
        AwardDO existingAward = awardMapper.selectById(awardDTO.getAwardId());
        if (existingAward == null) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "获奖信息不存在");
        }

        AwardDO awardDO = new AwardDO();
        awardDO.setAwardId(awardDTO.getAwardId());
        awardDO.setAwardName(awardDTO.getAwardName());
        awardDO.setAwardDate(awardDTO.getAwardDate());
        awardDO.setCompetitionName(awardDTO.getCompetitionName());
        awardDO.setTeacherId(awardDTO.getTeacherId());
        awardDO.setTeamMembers(awardDTO.getTeamMembers());
        awardDO.setStudentIds(awardDTO.getStudentIds());
        awardDO.setCertificateUrl(awardDTO.getCertificateUrl());
        awardDO.setUpdateBy(1); // Assuming current user ID is 1
        awardDO.setUpdateTime(new Date());

        return awardMapper.updateById(awardDO) > 0;
    }

    @Override
    public List<AwardDO> getAwards(Integer awardId) {
        QueryWrapper<AwardDO> wrapper = Wrappers.query();
        if (awardId != null) {
            wrapper.eq("award_id", awardId);
        }

        return awardMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public Boolean importAwards(AwardImportDTO awardImportDTO) {
        Path path = Paths.get(awardImportDTO.getFilePath());
        if (!Files.exists(path)) {
            throw new BusinessException(ResultCodeConstant.CODE_000001, "文件不存在");
        }

        try {
            List<String> lines = Files.readAllLines(path);
            List<AwardDO> awards = new ArrayList<>();
            for (String line : lines) {
                String[] parts = line.split(",");
                if (parts.length >= 7) {
                    AwardDO awardDO = new AwardDO();
                    awardDO.setAwardName(parts[0]);
                    awardDO.setAwardDate(Date.valueOf(parts[1]));
                    awardDO.setCompetitionName(parts[2]);
                    awardDO.setTeacherId(Integer.parseInt(parts[3]));
                    awardDO.setTeamMembers(parts[4]);
                    awardDO.setStudentIds(parts[5]);
                    awardDO.setCertificateUrl(parts[6]);
                    awardDO.setCreateBy(1); // Assuming current user ID is 1
                    awardDO.setCreateTime(new Date());
                    awardDO.setUpdateBy(1); // Assuming current user ID is 1
                    awardDO.setUpdateTime(new Date());
                    awards.add(awardDO);
                }
            }
            return awardMapper.insertBatchSomeColumn(awards) > 0;
        } catch (IOException e) {
            log.error("导入获奖信息失败", e);
            throw new BusinessException(ResultCodeConstant.CODE_000001, "导入失败");
        }
    }

    @Override
    @Transactional
    public Boolean exportAwards(AwardExportDTO awardExportDTO) {
        List<AwardDO> awards = awardMapper.selectList(Wrappers.emptyWrapper());
        StringBuilder sb = new StringBuilder();

        for (AwardDO award : awards) {
            sb.append(award.getAwardName()).append(",")
                    .append(award.getAwardDate()).append(",")
                    .append(award.getCompetitionName()).append(",")
                    .append(award.getTeacherId()).append(",")
                    .append(award.getTeamMembers()).append(",")
                    .append(award.getStudentIds()).append(",")
                    .append(award.getCertificateUrl()).append("\n");
        }

        try {
            FileUtils.writeStringToFile(new File(awardExportDTO.getFilePath()), sb.toString(), "UTF-8");
            return true;
        } catch (IOException e) {
            log.error("导出获奖信息失败", e);
            throw new BusinessException(ResultCodeConstant.CODE_000001, "导出失败");
        }
    }
}